<template>
  <div class="sign-input-wrapper">
    <h3
      v-show="!inputing"
      @click.stop="toInput($event)"
      :class="signColorClass"
    >
      {{ sign || defaultSign }}
    </h3>
    <input
      @click.stop
      v-show="inputing"
      type="text"
      :value="sign"
      @change.stop="renewSign($event)"
      @keydown.enter="blurSign($event)"
    />
  </div>
</template>

<script lang="ts" setup>
import { nextTick } from '@vue/runtime-core'
import { useEventListener } from '@vueuse/core'
import { computed, ref } from 'vue'

const props = defineProps<{
  url: string
  sign: string
  defaultSign: string
}>()

const emit = defineEmits<{
  (e: 'change', value: string): void
}>()

let inputing = ref(false)

let initSign = computed(() => {
  return props.sign ? props.sign : props.defaultSign
})
let signColorClass = computed(() => {
  return props.sign ? '' : 'colorUnmodified'
})

function toInput(e: any) {
  inputing.value = true
  nextTick(() => {
    let sib = e.target.nextSibling
    sib.focus()
    if (typeof sib.focus === 'function') e.target.nextSibling.select()
  })
}

function renewSign(e: any) {
  emit('change', e.target.value)
}

function blurSign(e: any) {
  e.target.blur()
  inputing.value = false
}

useEventListener(document.body, 'click', () => {
  inputing.value = false
})
</script>

<style scoped lang="scss">
.sign-input-wrapper {
  box-sizing: border-box;
  width: var(--w);
  height: var(--h);
  text-align: left;

  h3,
  input {
    box-sizing: border-box;

    position: absolute;
    top: 0;
    left: 0;
    // margin-left: calc(-1 * var(--fs));
    padding: 0 calc(var(--fs));
    display: block;
    width: var(--w);
    height: calc(var(--h) * 1.1);
    line-height: var(--h);
    font-size: var(--fs);
    color: var(--dark);

    &:hover {
      cursor: pointer;
    }
  }

  input {
    margin-top: calc(-1 * var(--h) * 0.05);
    border-radius: 3px;
    box-shadow: 0 0 3px var(--gray);
  }
}
</style>
